import { normalizeUrl } from '@web-utils/core'
import { Message } from 'element-ui'
import { buildDialog } from '@/util/dialog'
import '@web-utils/component/iframe-window/style.css'
import { toFileUrl } from '@/util/core'
import { server } from '@/config'

const onlyOfficeSupportFileTypes = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx']

const media = ['mp3', 'wav', 'mp4', 'flv']

const image = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']

const onlinePreviewSupportFileTypes = [
  ...onlyOfficeSupportFileTypes,
  'txt',
  'html',
  'htm',
  'asp',
  'jsp',
  'xml',
  'json',
  'properties',
  'md',
  'gitignore',
  'log',
  'java',
  'py',
  'c',
  'cpp',
  'sql',
  'sh',
  'bat',
  'm',
  'bas',
  'prg',
  'cmd',
  'ini',
  'js',
  'vue',

  'drawio',
  'vsd',
  'yaml',
  'yml',
  'xmind',
  'bpmn',
  'fbx',
  'ofd',
  'pdf',
  'zip',
  'rar',
  'jar',
  'tar',
  'gzip',
  'dwg'
]

/**
 * 文件预览
 * @returns {Promise<void>}
 */
const onlinePreviewFile = async file => {
  // watermarkTxt=${encodeURIComponent('动态水印')}&
  const openUrl = `${normalizeUrl(`${server}/preview-service`)}/onlinePreview?url=${encodeURIComponent(
    window.btoa(toFileUrl(file))
  )}`
  await buildDialog(() => import('@web-utils/component/iframe-window'), {
    props: {
      title: file.filename,
      url: openUrl
    }
  })
}

const previewVideoFile = async file => {
  await buildDialog(() => import('@/components/x-file-explorer-lite/FileViewer.vue'), {
    props: {
      file
    }
  })
}

const previewImageFile = async (file, files) => {
  await buildDialog(() => import('@/components/x-file-explorer-lite/ImageFileViewer.vue'), {
    props: {
      file,
      files
    }
  })
}

/**
 * 文件预览编辑
 * @param file
 * @param files
 * @returns {Promise<void>}
 */
export const openFile = async (file, files = null) => {
  files = files || [file]
  if (onlinePreviewSupportFileTypes.includes(file.format.toLowerCase())) {
    await onlinePreviewFile(file)
  } else if (media.includes(file.format.toLowerCase())) {
    await previewVideoFile(file)
  } else if (image.includes(file.format.toLowerCase())) {
    await previewImageFile(
      file,
      files.filter(value => {
        return value.format && image.includes(value.format.toLowerCase())
      })
    )
  } else {
    Message({ message: '暂不支持打开该类型的文件！', type: 'info' })
  }
}
